<?php

/**
 * Created by PhpStorm.
 * User: shwy
 * Date: 2017/8/1
 * Time: 20:40
 */

require_once './application/libraries/qiyuesuo/com.qiyuesuo.service.impl/RemoteSignServiceImpl.php'; //远程签接口
require_once './application/libraries/qiyuesuo/com.qiyuesuo.service.impl/SealServiceImpl.php';   //印章接口
require_once './application/libraries/qiyuesuo/com.qiyuesuo.common/Util.php'; //工具接口

class qiyuesuo extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->model('supplier_model');
        $this->load->model('biddingconfirm_model');
        $this->load->model('check_model');
    }


    public $url = Util::url;
    public $accessKey = Util::accessKey;
    public $accessSecret = Util::accessSecret;

    /**
     * 远程签接口初始化
     */
    private function remoteInit(){
        $SDk = new SDKClient($this->accessKey, $this->accessSecret, $this->url);

        $remoteSignServiceImpl = new RemoteSignServiceImpl($SDk);

        return $remoteSignServiceImpl;
    }

    /**
     * 印章接口初始化
     */
    private function sealInit(){
        $SDk = new SDKClient($this->accessKey, $this->accessSecret, $this->url);

        $sealServiceImpl  = new SealServiceImpl($SDk);

        return $sealServiceImpl;
    }

    /**
     * 由本地PDF文件上传生产
     */
    public function createByLocal(){


        $this->load->library('upload', __upload('bidding', 'bidding/confirm'));

        $upload = 'upload';
        $fileName = 'upload/bidding';
        $pathName = 'upload/bidding/confirm';

        if (!is_dir($upload)) {
            mkdir($upload);
        } else {
            if (!is_dir($fileName)) {
                mkdir($fileName);
            } else {
                if (!is_dir($pathName)) {
                    mkdir($pathName);
                }
            }
        }
        // 上传文件，
        // 
        // print_r($_POST);
        // print_r($_FILES);
        // die;

        //上传投标文件
        if ($this->upload->do_upload('dzPurchaseOrder')) {
            $dzPurchaseOrderData = $this->upload->data();
            // $dzPurchaseOrderFile = '/upload/bidding/confirm/' . $dzPurchaseOrderData['file_name'];
            $file_name = $this->config->item('qiyuesuo')['pdfpath'].'\\'.$dzPurchaseOrderData['file_name'];
            
        } else {
            $file_name =  $this->upload->display_errors();
        }

        // print_r($file_name);
        // die;

        $subject = "爱思特采购单";//todo 合同主题
        $expireTime = "2018-09-20";//合同过期时间；过期未结束签署，则作废，不传该参数则默认30天后过期。
        $docName = "languageRemote";//todo 合同文件名称
        $file = new \CURLFile(realpath($file_name));//合同文件

        $contract = new Contract();
        $contract->set_subject($subject);
        $contract->set_docName($docName);
        $contract->set_expireTime($expireTime);
        $contract->set_file($file);

        $result =  $this->remoteInit()->createByLocal($contract); //合同创建

        //合同创建成功之后,运营商默认签署
        if($result['message'] == 'SUCCESS'){
            /*
            $confirmData = [
                'confirm' => $_POST['supplierId'], //被签署的供应商id
                'status' => 2,
                'isEnd' => 1
            ];
            $confirmWhere = [
                //定标的关联标书id,唯一性.当做编辑的依据
                'relevanceId' => $_POST['relevanceId'],    //todo  需要的是定标数据的id 定标数据库的id
            ];
            $this->biddingconfirm_model->edit($confirmData,$confirmWhere); //编辑定标人员



            //编辑审核管理的数据
            $checkData = [
                'checkInfo' => $_COOKIE['username'], //当前来定标的用户名
                'status' => 1
            ];
            $checkWhere = [
                'id' => $_POST['checkId'],  //审核表的id
            ];
            $this->check_model->edit($checkData,$checkWhere); //编辑定标人员
*/
            //存储documentId并默认运营商签署完成
            $where = [
                'id' => $_POST['supplierId']  //供应商id
            ];
            $a = [
                0 => $result['documentId']  //多个订单则多叠加上去
            ];
            $supplierData = $this->supplier_model->getByFieldQueryData('id,name,linkMan,generateSeal,phone,documentId,registerNo',$where,0); //其他字段待确定

            //如果供应商之前签署过合同, 则就在尾后追加
            if($supplierData['documentId']){

                $supplierData['documentId'] = json_decode($supplierData['documentId'],true);

                array_push($supplierData['documentId'],$a[0]);

                $data = [
                    'documentId' => json_encode($supplierData['documentId'])
                ];
            }else{

                $data = [
                    'documentId' => json_encode($a)
                ];
            }


            $this->supplier_model->edit($data,$where);

            $documentId = $result['documentId'];
            $sealId = "2329969601420247253";//印章在契约锁的唯一标识

            $stamper = new Stamper();
            $stamper->set_offsetX(0);
            $stamper->set_offsetY(-0.03);
            $stamper->set_keyword("采购方（甲方）");
            // $stamper->set_keywordIndex(1);
            $signByPlatformResult = $this->remoteInit()->signByPlatform($documentId,$sealId,$stamper);//运营商签署

             $this->people($documentId,'爱思特科技','13588035060','爱思特科技',$stamper);
// $person = new Person();
//        $person->name='爱思特科技';
//        $person->mobile='45782136589';
//        $sealImageBase642 = $this->generateSeal("爱思特科技");

//            $this->remoteInit()->signByPerson($documentId,$person,$sealImageBase642['seal'],$stamper);


            //运营商签署成功之后,请求公司链接接口,发送url地址
            if($signByPlatformResult['message'] == 'SUCCESS'){
//        $str = file_get_contents('http://'.$_SERVER['HTTP_HOST'].'/upload/bidding/demo.jpg');
//        echo base64_encode($str);


                //根据documentID查询供应商的信息
                $documentId = $result['documentId'];


//                $str = file_get_contents('http://'.$_SERVER['HTTP_HOST'].$supplierData['generateSeal']);

                //印章图片的base64格式数据
                $str = file_get_contents($supplierData['generateSeal']);   //数据库内的数据为完整的url地址
                $sealImageBase64 = base64_encode($str);


                //todo 签署成功,返回的页面
                $successUrl = 'http://'.$_SERVER['HTTP_HOST'].'/api/qiyuesuo/complete?success=1&documentId='.$result['documentId'].'';


                $operation = "SIGN";

                $company = new Company();
                $company->name = $supplierData['name'];
                $company->registerNo = $supplierData['registerNo'];    //工商注册号

                $stamper = new Stamper();
                $stamper->set_offsetX(0);
                $stamper->set_offsetY(-0.03);
                $stamper->set_keyword("供应商（乙方）");
                // $stamper->set_keywordIndex(3);

                //企业用户连接注册
                $signUrlCompanyResult =  $this->remoteInit()->signUrlCompany($documentId,$sealImageBase64,$successUrl,$operation,$company,$stamper);

                    // __logInfo('契约锁Url',json_encode($signUrlCompanyResult));
                //如果公司签署成功之后发送链接到供应商短信
                if($signUrlCompanyResult['message'] == 'SUCCESS'){

                    // $this->people($documentId,$supplierData['linkMan'],$supplierData['phone'],$supplierData['name'],$stamper);
                    __logInfo('name',$supplierData['name']);
                    __logInfo('linkMan',$supplierData['linkMan']);

$this->people($documentId,$supplierData['linkMan'],$supplierData['phone'],$supplierData['name'],$stamper);
// $this->people($documentId,'爱思特科技','13588035060','爱思特科技',$stamper);

                    $this->load->library('Sms');
                    __logInfo('契约锁Url',$signUrlCompanyResult['signUrl']);
                    $num = __shortUrl($signUrlCompanyResult['signUrl']);
                    __logInfo('签署num',$num);
                    __logInfo('签署供应商手机号',$supplierData['phone']);

                    $pars = array(
                        'num' => "$num"   //必须是字符型
                    );
                    $res = $this->sms->run($supplierData['phone'], $this->config->item('aliyun_sms')['templateCode']['SMSTemplateCode'], $pars);
                    __logInfo('duanxin',$res);
                    if($res){

                        redirect('/admin/bidding/confirmList?page=1');
                        // print_r($signUrlCompanyResult['signUrl']);
                        // echo '短信发送成功';
                    }else{
                        // echo '短息发送失败';
                    }

                }else{
                    echo 123;
                    print_r($signUrlCompanyResult);
                }

            }else{
                echo 456;
                print_r($signByPlatformResult);
            }
        }else{
            echo 789;
            print_r($result);
        }

//        Array
//        (
//            [code] => 0
//            [documentId] =>
//            [message] => SUCCESS
//        )


    }



    /**
     * 签署完成
     */
    public function complete(){


        if(isset($_GET['success']) && $_GET['success'] == 1){
                    $documentId = $_GET['documentId'];
                    $result = $this->remoteInit()->complete($documentId);

//        Array ( [code] => 0 [message] => SUCCESS )
                  print_r($result);
        }

//        echo 12123123;
//
//        $this->load->view('/admin/success');



    }


    /**
     * 运营方签署
     * 关键字签署
     * 带签名外观
     */
    private function signByPlatform(){

        //todo 当点提交的时候,我们默认签署,这里只要获取到上面的返回值即可
        $documentId = "2330177047811575848 ";
        $sealId = "2329969601420247253";//印章在契约锁的唯一标识

        $stamper = new Stamper();
        $stamper->set_offsetX(0.1);
        $stamper->set_offsetY(-0.2);
        $stamper->set_keyword("甲方");
        $stamper->set_keywordIndex(-1);


        $result = $this->remoteInit()->signByPlatform($documentId,$sealId,$stamper);

        //todo 签署成功之后,发送短信通知供应商,  根据documentId查询供应商的信息

//        $arg = [
//            'documentId' =>
//        ];
        $this->supplier_model->getByFieldQueryData('id,phone',$arg,0);

        if($result['message'] == 'SUCCESS'){
            $this->load->library('Sms');

            $pars = array(
                'name' => '123456'
            );
            $res = $this->sms->run('13588035060', $this->config->item('aliyun_sms')['templateCode']['SMSTemplateCode'], $pars);

            if($res){
                echo '短信发送成功';
            }else{
                echo '短息发送失败';
            }

        }else{
            print_r($result);
        }

//            Array ( [code] => 0 [message] => SUCCESS )

        print_r($result);
    }


    /**
     * COMPANY（公司）签署页面链接
     */
    private function signUrlCompany(){

        $seal = $this->generateSeal();
        //todo 读取当前供应商的信息
//        $str = file_get_contents('http://'.$_SERVER['HTTP_HOST'].'/upload/bidding/demo.jpg');
//        echo base64_encode($str);


        //todo 根据documentID查询供应商的信息
        $data = [
            'documentId' => $result['documentId']

        ];
        $supplierData = $this->supplier_model->getByFieldQueryData('id,phone',$data,0);

        $documentId = "2330177047811575848 ";

        $sealImageBase64 = $seal['seal'];
        $successUrl = "http://118.89.161.43/success.html";   //todo 签署成功,返回的页面

        $operation = "SIGN";

        $company = new Company();
        $company->name = '上海信息科技股份有限公司';
        $company->registerNo = '1114447778547';    //todo 工商注册号

        $stamper = new Stamper();
        $stamper->set_page(1);
        $stamper->set_offsetX(0.2);
        $stamper->set_offsetY(0.1);
        $stamper->set_keyword("乙方");
        $stamper->set_keywordIndex(-1);


        $result =  $this->remoteInit()->signUrlCompany($documentId,$sealImageBase64,$successUrl,$operation,$company,$stamper);


        //todo 成功之后调用 签署完成接口
        print_r($result);

      /*
      Array (
        [code] => 0
        [signUrl] => https://expose.qiyuesuo.me/sign/remote?token=QWIvdDZnc1NQTmQramYxV0xwMEJJeFNmVUN5TGVxQkVraWowT0dvQWRZQzZXaitHZ0YyREZxOC9uZXM3dDllTw==
        [message] => SUCCESS
        [token] => QWIvdDZnc1NQTmQramYxV0xwMEJJeFNmVUN5TGVxQkVraWowT0dvQWRZQzZXaitHZ0YyREZxOC9uZXM3dDllTw== )
      */
    }

 /**
     * 用户信息接口
     * @
     */
   public function people($documentId,$name,$phone,$generateSealName,$stamper){
       $person = new Person();
       $person->name= $name;
       $person->mobile= $phone;
       $sealImageBase642 = $this->generateSeal($generateSealName);

       return $this->remoteInit()->signByPerson($documentId,$person,$sealImageBase642['seal'],$stamper);
   }



    /**
     * 生成企业电子印章
     */
    public function generateSeal($name){
        return $this->sealInit()->generatePersonalSeal($name);
    }




}
